/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tanqueDeAgua;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DecimalFormat;
import javax.swing.JSlider;
import javax.swing.SwingWorker;

/**
 *
 * @author pabloramix
 */
public class ControlBoard extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public ControlBoard() {
        initComponents();
        tanque = new Tank(100);
        entradas = new Pipe[3];
        controlEntradas = new JSlider[3];
        controlEntradas[0] = jSlider1;
        controlEntradas[1] = jSlider2;
        controlEntradas[2] = jSlider3;
        salidas = new Pipe[3];
        controlSalidas = new JSlider[3];
        controlSalidas[0] = jSlider6;
        controlSalidas[1] = jSlider4;
        controlSalidas[2] = jSlider5;

        jBtnAnnadirEntrada.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (int i = 0; i < entradas.length; i++) {
                    if (entradas[i] == null) {
                        entradas[i] = new Pipe(tanque, Pipe.Direction.IN, 0, "PipeIN_#" + (i + 1));
                        controlEntradas[i].setValue(0);
                        controlEntradas[i].addChangeListener(entradas[i]);
                        controlEntradas[i].setEnabled(true);
                        jBtnQuitarEntrada.setEnabled(true);
                        if (i == entradas.length - 1) {
                            jBtnAnnadirEntrada.setEnabled(false);
                        }
                        entradas[i].start();
                        break;
                    }
                }
            }
        });

        jBtnQuitarEntrada.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                for (int i = entradas.length - 1; i >= 0; i--) {
                    if (entradas[i] != null) {
                        entradas[i].terminate();
                        controlEntradas[i].setValue(0);
                        controlEntradas[i].setEnabled(false);
                        controlEntradas[i].removeChangeListener(entradas[i]);
                        entradas[i] = null;
                        jBtnAnnadirEntrada.setEnabled(true);
                        if (i == 0) {
                            jBtnQuitarEntrada.setEnabled(false);
                        }
                        break;
                    }
                }
            }
        });

        jBtnAnnadirSalida.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (int i = 0; i < salidas.length; i++) {
                    if (salidas[i] == null) {
                        salidas[i] = new Pipe(tanque, Pipe.Direction.OUT, 0, "PipeOUT_#" + (i + 1));
                        controlSalidas[i].setValue(0);
                        controlSalidas[i].addChangeListener(salidas[i]);
                        controlSalidas[i].setEnabled(true);
                        jBtnQuitarSalida.setEnabled(true);
                        if (i == salidas.length - 1) {
                            jBtnAnnadirSalida.setEnabled(false);
                        }
                        salidas[i].start();
                        break;
                    }
                }
            }
        });

        jBtnQuitarSalida.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (int i = salidas.length - 1; i >= 0; i--) {
                    if (salidas[i] != null) {
                        salidas[i].terminate();
                        controlSalidas[i].setValue(0);
                        controlSalidas[i].setEnabled(false);
                        controlSalidas[i].removeChangeListener(salidas[i]);
                        salidas[i] = null;
                        jBtnAnnadirSalida.setEnabled(true);
                        if (i == 0) {
                            jBtnQuitarSalida.setEnabled(false);
                        }
                        break;
                    }
                }
            }

        });

        worker.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {

                if (tanque.getLevel() >= tanque.getCapacity()) {
                    jProgressBar1.setIndeterminate(true);
                } else {
                    jProgressBar1.setIndeterminate(false);
                    jProgressBar1.setValue(worker.getProgress());
                }
            }
        });

        worker.execute();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jProgressBar1 = new javax.swing.JProgressBar();
        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jSlider1 = new javax.swing.JSlider();
        jBtnAnnadirEntrada = new javax.swing.JButton();
        jSlider2 = new javax.swing.JSlider();
        jBtnQuitarEntrada = new javax.swing.JButton();
        jSlider3 = new javax.swing.JSlider();
        jPanel2 = new javax.swing.JPanel();
        jBtnAnnadirSalida = new javax.swing.JButton();
        jSlider4 = new javax.swing.JSlider();
        jBtnQuitarSalida = new javax.swing.JButton();
        jSlider5 = new javax.swing.JSlider();
        jSlider6 = new javax.swing.JSlider();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("PCYTR -- Actividad 1");

        jProgressBar1.setOrientation(1);
        jProgressBar1.setToolTipText("");

        jLabel1.setText("jLabel1");
        jLabel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Entrada"));

        jSlider1.setMajorTickSpacing(10);
        jSlider1.setMinorTickSpacing(5);
        jSlider1.setPaintTicks(true);
        jSlider1.setSnapToTicks(true);
        jSlider1.setValue(0);
        jSlider1.setEnabled(false);

        jBtnAnnadirEntrada.setText("+");
        jBtnAnnadirEntrada.setToolTipText("");

        jSlider2.setMajorTickSpacing(10);
        jSlider2.setMinorTickSpacing(5);
        jSlider2.setPaintTicks(true);
        jSlider2.setSnapToTicks(true);
        jSlider2.setValue(0);
        jSlider2.setEnabled(false);

        jBtnQuitarEntrada.setText("-");
        jBtnQuitarEntrada.setToolTipText("");
        jBtnQuitarEntrada.setEnabled(false);

        jSlider3.setMajorTickSpacing(10);
        jSlider3.setMinorTickSpacing(5);
        jSlider3.setPaintTicks(true);
        jSlider3.setSnapToTicks(true);
        jSlider3.setValue(0);
        jSlider3.setEnabled(false);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jSlider3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jSlider2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jBtnAnnadirEntrada, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBtnQuitarEntrada, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBtnAnnadirEntrada))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSlider2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBtnQuitarEntrada))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSlider3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(12, 12, 12))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Salida"));

        jBtnAnnadirSalida.setText("+");
        jBtnAnnadirSalida.setToolTipText("");

        jSlider4.setMajorTickSpacing(10);
        jSlider4.setMinorTickSpacing(5);
        jSlider4.setPaintTicks(true);
        jSlider4.setSnapToTicks(true);
        jSlider4.setValue(0);
        jSlider4.setEnabled(false);

        jBtnQuitarSalida.setText("-");
        jBtnQuitarSalida.setToolTipText("");
        jBtnQuitarSalida.setEnabled(false);

        jSlider5.setMajorTickSpacing(10);
        jSlider5.setMinorTickSpacing(5);
        jSlider5.setPaintTicks(true);
        jSlider5.setSnapToTicks(true);
        jSlider5.setValue(0);
        jSlider5.setEnabled(false);

        jSlider6.setMajorTickSpacing(10);
        jSlider6.setMinorTickSpacing(5);
        jSlider6.setPaintTicks(true);
        jSlider6.setSnapToTicks(true);
        jSlider6.setValue(0);
        jSlider6.setEnabled(false);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jSlider5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jSlider4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jSlider6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jBtnAnnadirSalida, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBtnQuitarSalida, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jBtnAnnadirSalida)
                    .addComponent(jSlider6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSlider4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBtnQuitarSalida))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSlider5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(12, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(6, 6, 6)
                        .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(10, 10, 10)
                        .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ControlBoard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ControlBoard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ControlBoard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ControlBoard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ControlBoard().setVisible(true);

            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBtnAnnadirEntrada;
    private javax.swing.JButton jBtnAnnadirSalida;
    private javax.swing.JButton jBtnQuitarEntrada;
    private javax.swing.JButton jBtnQuitarSalida;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JSlider jSlider1;
    private javax.swing.JSlider jSlider2;
    private javax.swing.JSlider jSlider3;
    private javax.swing.JSlider jSlider4;
    private javax.swing.JSlider jSlider5;
    private javax.swing.JSlider jSlider6;
    // End of variables declaration//GEN-END:variables

    private Tank tanque;
    private Pipe[] entradas;
    private Pipe[] salidas;
    private JSlider[] controlEntradas;
    private JSlider[] controlSalidas;

    final SwingWorker worker = new SwingWorker<Void, Integer>() {
        @Override
        protected Void doInBackground() throws Exception {
            
            DecimalFormat df = new DecimalFormat("##0.00");
            
            while (true) {

                double caudalEnt = 0.0;
                double caudalSal = 0.0;
                String text1Ent = "";
                String text2Ent = "";
                String text1Sal = "";
                String text2Sal = "";

                setProgress((int) tanque.getLevel());

                for (int i = 0; i < entradas.length && entradas[i] != null; i++) {
                    caudalEnt += entradas[i].getCaudal();
                    text1Ent += "<p>Entrada " + (i + 1) + ": " + entradas[i].getCaudal() + " L/s</p>";
                    text2Ent += "<p>" + entradas[i].getStatusString() + "</p>";
                }
                for (int i = 0; i < salidas.length && salidas[i] != null; i++) {
                    caudalSal += salidas[i].getCaudal();
                    text1Sal += "<p>Salida " + (i + 1) + ": " + salidas[i].getCaudal() + " L/s</p>";
                    text2Sal += "<p>" + salidas[i].getStatusString() + "</p>";
                }
                
                String text = "<html>" + text1Ent
                        + "<p>Entrada total: " + caudalEnt + " L/s</p><br/>"
                        + text1Sal
                        + "<p>Salida total: " + caudalSal + " L/s</p><br/>"
                        + "<p>Volumen: " + df.format(tanque.getContent()) + " L</p>"
                        + "<p>Capacidad: " + (tanque.getContent() >= tanque.getCapacity() ? "Rebasada" : tanque.getLevel() + "%") 
                        + " (max. " + tanque.getCapacity() + " L)</p><br/>"
                        + "<p>=====================</p>"
                        + "<br><p>Threads:"
                        + ( (text2Ent.isEmpty() && text2Sal.isEmpty()) ? " [N/A]</p>" : "</p><br/>" )
                        + text2Ent + ( (!text2Ent.isEmpty()) ? "<br/>"+ text2Sal : text2Sal ) + "</html>";
                jLabel1.setText(text);

                Thread.sleep(200);
            }
        }
    };

}
